let isFloatingWindowVisible = true;

$(window).on("load", function () {
  // 添加新的按钮
  const $toggleButton = $("<button>", {
    id: "toggle-product-viewer",
    text: "切换商品查看器",
    css: {
      position: "fixed",
      top: "10px",
      left: "10px",
      zIndex: 1000,
      padding: "10px",
      backgroundColor: "#4CAF50",
      color: "white",
      border: "none",
      borderRadius: "5px",
      cursor: "pointer",
    },
  });

  $toggleButton.on("click", toggleProductViewer);
  $("body").append($toggleButton);

  chrome.runtime.sendMessage({ action: "autoOpenProductViewer" }, (result) => {
    console.log(result);
    if (result.floatingWindowOn) {
      toggleProductViewer();

      const urlParams = new URLSearchParams(window.location.search);
      const keyword = urlParams.get("keyword");
      if (keyword) {
        $("#search-input").val(decodeURIComponent(keyword));
      }
    }
  });

  function removeQRCodeDiv() {
    $("div.jTdCode.fixed").remove();
  }
  removeQRCodeDiv();
});

function extractProductInfo() {
  const products = $(".jSearchListArea .jItem")
    .map(function () {
      const $item = $(this);
      return {
        id: $item.find(".e-attention").data("id"),
        url: $item.find(".jPic a").attr("href"),
        mainImage: $item.find(".jPic img").attr("src"),
        price: $item.find(".jdNum").text().trim(),
        commentCount: $item.find(".jCommentNum").text().trim(),
        name: $item.find(".jDesc a").text().trim(),
        wraps: $item
          .find(".jScrollWrap li")
          .map(function () {
            const $li = $(this);
            return {
              id: $li.attr("sid"),
              url: $li.data("href"),
              image: $li.data("src"),
              thumbnail: $li.find("img").attr("src"),
              title: $li.find("a").attr("title"),
            };
          })
          .get(),
      };
    })
    .get();
  return products;
}

function createFloatingWindow() {
  const $floatingWindow = $("<div>", { id: "jd-product-viewer" });
  const page = $("div.jPage > a.current").text();
  const totalPage = $("div.jPage > a:nth-last-child(2)").text();
  const shopName = $("div.jLogo > a").text();
  const totalProductCount = $(".jTotal em").text();

  $floatingWindow.html(`
        <div class="header">
          <h2>${shopName} <div id="shop-rating" class="jshop-star"></div></h2>
          <div class="header-buttons">
            <div class="search-container">
                <input type="text" id="search-input" placeholder="搜索商品...">
                <button id="search-btn">搜索</button>
            </div>
          </div>
          <button id="close-viewer-btn">×</button>


        </div>
        <div id="jDimension">
        </div>
        <div id="products"></div>
        <div id="loading" style="display: none;">Loading...</div>
        <div class="pagination-buttons">
          <button id="prev-page-btn">上一页</button>
          <div id="page-info">
            <span>第${page}页 / 共${totalPage}页</span>
            <span>共${totalProductCount}件商品</span>
          </div>
          <button id="next-page-btn">下一页</button>
        </div>
    `);

  $("body").append($floatingWindow);

  const $shopRating = $("div.jRating > a > div > ul").clone();
  const $jDimension = $("div.jDimension").clone();
  const $searchKeyword = $("div.jSearch > div > dl").clone();
  $floatingWindow.find("#shop-rating").append($shopRating);
  $floatingWindow.find("#jDimension").append($jDimension);
  $floatingWindow.find("#jDimension .jModulesTitle").append($searchKeyword);

  $floatingWindow
    .find("#jDimension #price-search-btn")
    .on("click", searchByPrice);
  $floatingWindow.find("#search-btn").on("click", searchProduct);
  const $toggleDimension = $(`
    <div class="toggle-dimension">
      <span class="toggle-text">展开更多</span>
      <i class="toggle-icon">▼</i>
    </div>
  `);

  $floatingWindow.find("span.selectMore").remove();

  const $jDimensionSelec = $jDimension.find(".jDimensionSelec");

  const $expandAllBtn = $(`
  <div class="expand-all-container">
    <button id="expand-all-btn" class="expand-all-btn">展开全部</button>
  </div>
`);

  $expandAllBtn.on("click", function () {
    const $jMoreOptionsDiv = $jDimension.find("#JMoreOptionsDiv_0");
    const $button = $expandAllBtn.find("#expand-all-btn");

    if ($jMoreOptionsDiv.is(":hidden")) {
      $jMoreOptionsDiv.show();
      $button.text("收起全部");
    } else {
      $jMoreOptionsDiv.hide();
      $button.text("展开全部");
    }
  });

  $jDimensionSelec.append($expandAllBtn);

  const $toggleText = $toggleDimension.find(".toggle-text");
  const $toggleIcon = $toggleDimension.find(".toggle-icon");
  // 默认折叠状态
  $jDimensionSelec.removeClass("expanded");
  $toggleText.text("展开更多");
  $toggleIcon.text("▼");

  $toggleDimension.on("click", function () {
    $jDimensionSelec.toggleClass("expanded");
    $toggleDimension.toggleClass("expanded");
    if ($jDimensionSelec.hasClass("expanded")) {
      $toggleText.text("收起");
      $toggleIcon.text("▲");
    } else {
      $toggleText.text("展开更多");
      $toggleIcon.text("▼");
    }
  });

  $floatingWindow
    .find("#jDimension div.jModulesTitle")
    .append($toggleDimension);

  $("#close-viewer-btn").on("click", toggleProductViewer);
  $("#prev-page-btn").on("click", () => navigateToPage("prev"));
  $("#next-page-btn").on("click", () => navigateToPage("next"));

  // Add keydown event listener for arrow keys
  $(document).on("keydown", handleKeyNavigation);
  return $floatingWindow;
}

function createOrUpdateProductElement(productInfo, $existingElement = null) {
  const { name, mainImage, url, price, commentCount, wraps } = productInfo;
  const reviewsCount = parseInt(commentCount, 10);

  if ($existingElement) {
    if ($existingElement.find(".main-image").attr("src") !== mainImage) {
      $existingElement.find(".main-image").attr("src", mainImage);
    }
    if (price != 0) {
      $existingElement.find(".price").text(`￥${price}`);
    }
    const $existingWraps = $existingElement.find(".wraps-container img");
    wraps.forEach((wrap, index) => {
      if (index < $existingWraps.length) {
        const $existingWrap = $($existingWraps[index]);
        if ($existingWrap.attr("src") !== wrap.thumbnail) {
          $existingWrap.attr("src", wrap.thumbnail);
        }
        if ($existingWrap.attr("alt") !== wrap.title) {
          $existingWrap.attr("alt", wrap.title);
        }
        if ($existingWrap.data("url") !== wrap.url) {
          $existingWrap.data("url", wrap.url);
        }
      } else {
        $existingElement
          .find(".wraps-container")
          .append(
            `<img src="${wrap.thumbnail}" alt="${wrap.title}" class="wrap-image" data-url="${wrap.url}">`
          );
      }
    });
    return $existingElement;
  }
  let $productDiv = $("<div>", { class: "product" });
  $productDiv.html(`
        <button class="close-product">×</button>
        <img src="${mainImage}" alt="${name}" class="main-image">
         <div class="wraps-container"></div>
        <div class="product-info">
            <h3>${name}</h3>
            <div class="price-reviews">
                <p class="price">${price == 0 ? "暂无价格" : `￥${price}`}</p>
                <p class="reviews ${
                  reviewsCount > 1 ? "highlighted" : ""
                }">${commentCount}条评价</p>
            </div>
        </div>
    `);

  // Add wraps (子图)
  const $wrapsContainer = $productDiv.find(".wraps-container");
  wraps.forEach((wrap) => {
    $wrapsContainer.append(
      `<img src="${wrap.thumbnail}" alt="${wrap.title}" class="wrap-image" data-url="${wrap.url}">`
    );
  });

  // Main image click event
  $productDiv.find(".main-image").on("click", function (e) {
    e.stopPropagation();
    openInNewTab(url);
  });

  // Wrap images click event
  $productDiv.find(".wrap-image").on("click", function (e) {
    e.stopPropagation();
    openInNewTab($(this).data("url"));
  });

  // Close button click event
  $productDiv.find(".close-product").on("click", function (e) {
    e.stopPropagation();
    $productDiv.remove();
  });
  return $productDiv;
}

function toggleProductViewer() {
  let $floatingWindow = $("#jd-product-viewer");

  if ($floatingWindow.length === 0) {
    $floatingWindow = createFloatingWindow();
  }

  if (isFloatingWindowVisible) {
    $floatingWindow.show();
    initializeProductViewer();
  } else {
    $floatingWindow.hide();
  }

  isFloatingWindowVisible = !isFloatingWindowVisible;
}

function openInNewTab(url) {
  window.open(url, "_blank");
}

function initializeProductViewer() {
  window.scrollTo({
    top: 0,
    behavior: "instant",
  });

  setTimeout(() => {
    // 平滑滚动到指定位置
    window.scrollTo({
      top: 700,
      behavior: "smooth",
    });
  }, 500);

  function onScrollOnce() {
    if (window.scrollY > 600) {
      setTimeout(() => {
        loadMoreProducts();
      }, 200);
      // 移除事件监听器，确保只触发一次
      window.removeEventListener("scroll", onScrollOnce);
    }
  }

  window.addEventListener("scroll", onScrollOnce);

  const $container = $("#products");
  console.log($container);
  if ($container.length) {
    loadMoreProducts();

    $container.on("scroll", function () {
      const containerScrollPercentage =
        $container.scrollTop() /
        ($container[0].scrollHeight - $container.height());
      const windowScrollTarget =
        containerScrollPercentage * ($(document).height() - $(window).height());

      $(window).scrollTop(windowScrollTarget + 600);

      if (
        $container.scrollTop() + $container.height() <
        $container[0].scrollHeight - 50
      ) {
        loadMoreProducts();
      }
    });
  }
}

function loadMoreProducts() {
  const $loadingElement = $("#loading").show();
  const newProducts = extractProductInfo();

  if (newProducts.length === 0) {
    $loadingElement.text("No more products to load.");
    isLoading = false;
    return;
  }

  const $container = $("#products");

  if ($container.length === 0) {
    console.error("Products container not found");
    isLoading = false;
    return;
  }

  const $existingProducts = $container.children();
  $.each(newProducts, function (index, newProduct) {
    if (index < $existingProducts.length) {
      createOrUpdateProductElement(newProduct, $($existingProducts[index]));
    } else {
      $container.append(createOrUpdateProductElement(newProduct));
    }
  });

  $existingProducts.slice(newProducts.length).remove();

  isLoading = false;
  $loadingElement.hide();
}

function handleKeyNavigation(e) {
  if ($("#jd-product-viewer").is(":visible")) {
    if (e.key === "ArrowLeft") {
      navigateToPage("prev");
    } else if (e.key === "ArrowRight") {
      navigateToPage("next");
    }
  }
}

function navigateToPage(direction) {
  const prevPage = $("div.jPage  a:first-of-type");
  const nextPage = $("div.jPage  a:last-of-type");
  let newPage;
  if (direction === "prev") {
    newPage = prevPage.attr("href");
  } else if (direction === "next") {
    newPage = nextPage.attr("href");
  }

  if (newPage && newPage !== window.location.href) {
    window.location.href = newPage;
  }
}

function searchProduct() {
  const searchTerm = $("#jd-product-viewer #search-input").val().trim();
  console.log(searchTerm);
  if (searchTerm) {
    // 获取当前 URL
    let currentUrl = window.location.href;

    // 检查 URL 是否已经包含查询参数
    const hasQueryParams = currentUrl.includes("?");

    // 检查 URL 是否已经包含 keyword 参数
    const hasKeyword = currentUrl.includes("keyword=");

    if (hasKeyword) {
      // 如果已经有 keyword，替换它的值
      currentUrl = currentUrl.replace(
        /keyword=[^&]*/,
        `keyword=${encodeURIComponent(searchTerm)}`
      );
    } else {
      // 如果没有 keyword，添加它
      currentUrl += hasQueryParams ? "&" : "?";
      currentUrl += `keyword=${encodeURIComponent(searchTerm)}`;
    }

    // 跳转到新的 URL
    window.location.href = currentUrl;
  }
}

function searchByPrice() {
  const minPrice = $("#jDimension #min-price-input").val().trim();
  const maxPrice = $("#jDimension #max-price-input").val().trim();

  // 获取当前 URL 的基础部分（不包含查询字符串）
  let baseUrl = window.location.href.split("?")[0];

  // 从baseUrl中提取需要的部分
  let urlParts = baseUrl.split("-");

  // 如果输入了有效的价格范围
  if (minPrice && maxPrice) {
    urlParts[6] = minPrice;
    urlParts[7] = maxPrice;
  }

  // 重新组合URL
  let newUrl = urlParts.join("-");

  // 跳转到新的 URL
  window.location.href = newUrl;
}
